package com.example.computer_exam_training_sys.ultils;

import com.baidubce.appbuilder.console.appbuilderclient.AppBuilderClient;
import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientIterator;
import com.baidubce.appbuilder.model.appbuilderclient.AppBuilderClientResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.SocketTimeoutException;

//用于连接百度千帆agent的功能类
@Component
public class BaiduTokenUtil {

    @Value("${baidu.appbuilder.token}")
    private String appBuilderToken;

    @Value("${baidu.appbuilder.agentId}")
    private String appId;

    public String getAnswer(String query) throws SocketTimeoutException {
        try {
            System.setProperty("APPBUILDER_TOKEN", appBuilderToken);

            AppBuilderClient client = new AppBuilderClient(appId);
            String conversationId = client.createConversation();

            AppBuilderClientIterator itor = client.run(query, conversationId, new String[]{}, false);
            StringBuilder sb = new StringBuilder();
            while (itor.hasNext()) {
                AppBuilderClientResult result = itor.next();
                sb.append(result.getAnswer());
            }
            return sb.toString();
        } catch (SocketTimeoutException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            return "调用千帆 Agent 出错: " + e.getMessage();
        }
    }
}
